<template>
<!-- 关联视图关系展示（echarts tree） -->
  <div style="width:100%;height: calc(100% - 30px); overflow:auto;text-align:center">
    <div v-if="isShowEchartsDome" id="eleViewTree" style="width:125%; background:white; min-height:  calc(100% - 20px);"></div>
    <el-button v-if="!isShowEchartsDome" @click="showpup"  class="el-icon-circle-plus">添加关联关系</el-button>
  </div>
</template>
<script>
import {QUERYELEVANCEVIEW,assoViewMaintain} from '@api/url'
export default {
  data(){
    return{
      spanArr:[],
      myChart:null,
      eleviewsData:[],
      isShowEchartsDome:true,//默认展示
      pos:null,
      ListArow:[],
      slaveId:"",
      content:{},
       option:{
        axisExpandable:{
          rootToNode:true
        },
        containLabel:true,
          series:[
            {
                type: 'tree',
                collapsed:false,
                // path:"../../assets/image/make.png",
                symbol: "image://@images/make/delete.png",//影藏圆圈
                isExpand:true,
                symbolSize: 16,
                roam: "move",//如果只想要开启缩放或者平移，可以设置成 'scale' 或者 'move'。设置成 true 为都开启
                id: 0,
                name: 'tree1',
                data: [],
                labelLine: { // 设置指示线的长度
                  normal: {
                    length: 2,
                    length2: 2
                  }
                },
                 itemStyle: {
                    borderWidth:0,
                    borderColor: '#c23531',
                    emphasis: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'blue',
                       
                    }
                  },
                top: '1%',
                left: '12%',//距离容器
                bottom: '10%', //距离底部
                right: '40%', //右侧宽度

                // edgeShape: 'polyline', 直线
                edgeForkPosition: '90%',//树占高度
                initialTreeDepth: 4,

                lineStyle: {
                    width: 2 //线粗
                },

                label: {
                    backgroundColor: '#fff',
                    position: 'left',
                    verticalAlign: 'bottom',
                    align: 'right',
                    show:true,
                    fontSize:16
                },

                leaves: {
                    label: {
                        position: 'right',
                        verticalAlign: 'bottom',
                        align: 'left'
                    }
                },

                emphasis: {
                    focus: 'self',
                    blurScope: 'descendant'
                },

                expandAndCollapse: true,
                animationDuration: 0,
                animationDurationUpdate: 0
            }
        ]
       }
      
    }
  },
  props:{
    menuData:{
      type:Object,
      default:null
    },
    showeleviewsData:{
      type:Object,
      default:null
    },
  },
  watch:{
    menuData(val){
      console.log(val,'选中的数据为----------------------')
      // this.isShowEchartsDome=false
       this.queryElevanceViews(val)
    }
  },
  
  mounted() {
    this.queryElevanceViews()
    
  },
  methods:{
    //关闭当前页面
    closeBox(){
      this.$emit('closePage')
    },
    showpup(){
      this.$emit('closePage','showpup')
    },
    // 将数据进行重组，适应echarts反显
    recombination(){
      this.detailData={}
      // 删除图标 编辑图标
      let makePath = `image://${require("../../../assets/image/make.png")}`
      let delpath=`image://${require("../../../assets/image/delete.png")}`
      if (this.content.length>0) {
        this.detailData.name=this.content[0].masterTableName//主表名称赋值
        this.detailData.symbol="none",//默认无图标
        this.detailData.tierId='1'//设置层级，便于确定点击事件判断 主表层
        this.detailData.children=[]//关联关系名称，取决于有几条关联数据 
        this.content.forEach(ele=>{
          this.detailData.children.push({
            name:this.getLabel(ele.relationType),//赋值关联关系
            tierId:"2",//设置层级，便于确定点击事件判断 关联关系层
            symbolSize:18, 
            symbol:makePath,
            masterId: ele.masterId,
            masterTableName: ele.masterTableName,
            modelId: ele.modelId,
            optMode: ele.optMode,
            relationId: ele.relationId,
            relationType: ele.relationType,
            seqno: ele.seqno,
            showPost: ele.showPost,
            slaveId: ele.slaveId,
            slaveTableName: ele.slaveTableName,
            children:[{
              name:ele.slaveTableName,
              tierId:"3", //设置层级，便于确定点击事件判断 关联表民称层
              relationId:ele.relationId, //关联id
              modelId:ele.modelId, //模型id 
              symbolSize:18,
              symbol:delpath,
              slaveId: ele.slaveId,
              children:[]
              }]//存辅表名称
          })
          ele.lists.forEach(item=>{//把字段赋值到
            this.detailData.children.forEach(child=>{
              if (child.relationId==ele.relationId) {
                child.children[0].children.push({
                  tierId:"4", //设置层级，便于确定点击事件判断 字段层
                  name:`主表字段：${item.masterShowfld}——辅表字段：${item.slaveShowfld}`,
                  symbol:"none",
                  relationId:item.relationId,
                  modelId:ele.modelId,
                  slaveId:item.slaveId,
                  relationType:item.relationType,
                  relationTypelabel:this.getLabel(item.relationType),
                  slaveTableName:item.slaveTableName,
                  masterTableName:item.masterTableName,
                  masterId:ele.modelId,
                  masterShowfld:item.masterShowfld,
                  slaveShowfld:item.slaveShowfld,
                  sFldType:item.sFldType,
                  mFldType:item.mFldType
                })
              }
            })
          })
        })
        this.option.series[0].data[0]=this.detailData
      }else{
        this.option.series[0].data[0]={name:"暂无数据"}
      }
      this.creatTree()
    },
    //渲染echarts tree
    creatTree(){
      let chartDom = document.getElementById('eleViewTree');
      let myChart = this.$echarts.init(chartDom); 
      //防止出现“There is a chart instance already initialized on the dom.”的警告    
      //在使用echarts发现需要及时对新建的myChart实例进行销毁,否则会出现上述警告 
      setTimeout(myChart.setOption(this.option), 500);
      myChart.on('click', params=>{
        if (params.componentType === 'series') {
                // dataIndex  2 点击编辑 
                // data index 3 点击删除
                if (params.data.tierId=='2') {
                  this.modify(params.data.children[0].children)
                //  alert('点击了编辑按钮')
                }else if (params.data.tierId=='3') {
                  // alert('点击了删除按钮')
                  this.$confirm('此操作删除该记录, 是否继续?', '提示', '确认信息', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    center: true
                  }).then(() => {
                    // 确认删除
                      this.deleteData(params.data)
                    }).catch(action => {
                      this.isShowEchartsDome=true
                      this.queryElevanceViews()
                      console.log("取消删除")
                    });
                }
          
          }
      });
    },    
    // 查询关联视图
    queryElevanceViews(){
      let param={
        "modelId":this.menuData.menuId
      }
      this.isShowEchartsDome=true 
      this.$http.post(QUERYELEVANCEVIEW,param).then(res=>{
        console.log('selectDemo查询关联视图信息成功')
        console.log(res)
        this.content=res.data.data
          if(res.data.code=='200' && res.data.data.length>0){
            // this.ListArow=[]
            res.data.data.forEach(item=>{
              item.lists.forEach(ele=>{
              ele.relationId=item.relationId;
              ele.modelId=item.modelId;
              ele.slaveId=item.slaveId;
              ele.relationType=item.relationType;
              ele.relationTypelabel=this.getLabel(item.relationType)
              ele.masterTableName=item.masterTableName
              ele.slaveTableName=item.slaveTableName;
              // this.ListArow.push(ele)
            })
          })
          }else{
            this.isShowEchartsDome=false
          }
          // 将数据进行重组，适应echarts反显
          this.recombination()
      }).catch(err=>{
        this.content={}
        this.isShowEchartsDome=false
        console.log('查询关联视图信息失败')
        console.log(err)
      })
    },
    // 将关联类型key值进行转换
    getLabel(relationType){
      let arr=[{value:1,label:"1:1"},{value:2,label:"1:N"},{value:2,label:"N:1"},{value:2,label:"N:N"}]
      let label=""
      arr.forEach(ele=>{
        if (relationType==ele.value) {
          label=ele.label
        }
      })
      return label
    },
                  
   
    //修改
    modify(data){
      //主表id  modelId
      // 附表id ：slaveId
      // 关联id：relationId
      this.$emit('tagisShowpup',data,{modelId:this.menuData.menuId,slaveId:this.menuData.slaveId})
    },
    //删除
    deleteData(data){
      let param={
         optMode:"D",
          relationId:data.relationId, //关联id
          modelId:data.modelId, 
          slaveId:data.slaveId  //从表id
      }
      this.$http.post(assoViewMaintain,param).then(res=>{
        console.log(res)
        if (res.data.code=="200") {
          this.$confirm('删除成功', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          })
          this.queryElevanceViews()
        }else{
          this.$confirm(res.data.message, '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
        }
      }).catch(err=>{
        console.log(err)
        this.$confirm('删除失败', '提示', {
            confirmButtonText: '确定',
            type: 'fail'
          })
      })
    },
  }
}
</script>
<style lang="less" scoped>
  .elevanceViewscontent{
    width: 100%;
    margin-top:10px ;
    text-align: center;
    height: calc(100% - 1px);
    overflow: scroll;
  }
</style>